package com.qf.util;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * projectName:mybatis_demo
 * author:刘哥
 * time:2022/7/6 16:48
 * description:
 */
public class MyBatisUtils {
    //获得SqlSession工厂
    private static SqlSessionFactory factory;
//    创建线程绑定连接
    private static ThreadLocal<SqlSession> threadLocal=new ThreadLocal<>();
    static {
//        读取配置文件
        try {
            InputStream is = Resources.getResourceAsStream("mybatis.xml");
            factory = new SqlSessionFactoryBuilder().build(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
//    获取连接
    public static SqlSession openSession(){
//        创建连接对象
        SqlSession sqlSession = factory.openSession();
//        将连接保存到线程
        threadLocal.set(sqlSession);
        return sqlSession;
    }
//    提交事务
    public static void commit(){
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null) {
            sqlSession.commit();
        }
    }
//事务回滚
    public static void rollback(){
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null) {
            sqlSession.rollback();
        }
    }
//关闭事务
    public static void close(){
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession != null) {
            sqlSession.close();
//            关闭事务后移除连接，防止内存泄漏
            threadLocal.remove();
        }
    }
    public static  <T extends Object> T getMapper(Class<T> clazz){
        SqlSession sqlSession = threadLocal.get();
        if (sqlSession == null) {
             sqlSession = openSession();

        }
        return sqlSession.getMapper(clazz);
    }
}

